package com.dsl.tms.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.dsl.tms.datasource.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置
 */
@Configuration
public class DataSourceConfig {

    @Value("${tmsdb.url}")
    private String tmsDBUrl;

    @Value("${tmsdb.driver-class-name}")
    private String tmsDriverClassName;

    @Value("${tmsdb.username}")
    private String tmsUserName;

    @Value("${tmsdb.password}")
    private String tmsPassword;

    @Bean(name = "dynamicDataSource")
    public DynamicDataSource dynamicDataSource(){
        DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();

        DruidDataSource tmsDataSource = new DruidDataSource();
        tmsDataSource.setDriverClassName(tmsDriverClassName);
        tmsDataSource.setUrl(tmsDBUrl);
        tmsDataSource.setUsername(tmsUserName);
        tmsDataSource.setPassword(tmsPassword);

        Map<Object,Object> map = new HashMap<Object, Object>();
        map.put("tms",tmsDataSource);
        dynamicDataSource.setTargetDataSources(map);
        dynamicDataSource.setDefaultTargetDataSource(tmsDataSource);
        return dynamicDataSource;
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        return bean.getObject();
    }

    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
